<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: pl125 <xskjs888@163.com>
// +----------------------------------------------------------------------

namespace api\admin\model;

use api\common\model\CommonModel;
use api\util\Time;

class ToiletFlowModel extends CommonModel
{
    // 可查询字段
    // protected $visible = [
    //     'id', 'start_time', 'end_time', 'man_num', 'woman_num','flow_num','titile','position','create_time',
    // ];
    //模型关联方法
    // protected $relationFilter = ['articles'];

    /**
     * 基础查询
     */
    // protected function base($query)
    // {
    //     $query->alias('toilet')->where('toilet.status', 1);
    // }
    /**
     * 关联
     * @return $this
     */
    // public function articles()
    // {
    //     return $this->belongsToMany('PortalPostModel','portal_tag_post','post_id','tag_id');
    // }

    /**
     * [getDetailsNumber 获取人流量统计]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $mac      [description]
     * @param    [type]     $dateTime [description]
     * @return   [type]               [description]
     */
    public function getDetailsNumber($mac, $type, $userTime, $dateTime)
    {
        switch ($type)
        {
            case '3':
                return $this->getYearDetails($mac, $userTime, $dateTime);
            case '2':
                return $this->getMonthDetails($mac, $userTime, $dateTime);
            default:
                return $this->getLineDetails($mac, $dateTime);
                break;
        }

    }

    /**
     * [getYearDetails description]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getYearDetails($mac, $userTime, $dateTime)
    {
        if (strtotime($userTime) && strlen($userTime) == 4)
        {

            $result = $this->field('FROM_UNIXTIME(create_time, "%Y-%m") as times,sum(user_in) as in_num')
                ->where('master_mac', $mac)
                ->whereTime('create_time', 'between', [$userTime . '-1-1', $userTime . '-12-31'])
                ->group('times')
                ->select()->toArray();
            $tmpData = $this->yearArrToeasy($userTime, $dateTime);
            return $this->mergeDetailsNum($result, $tmpData);
        }
    }

    /**
     * [getMonthDetails 获取月度详情]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function getMonthDetails($mac, $userTime, $dateTime)
    {
        if (strlen($userTime) != 4)
        {
            $tmp    = $this->getMonth($userTime);
            $result = $this->field('FROM_UNIXTIME(create_time, "%m-%d") as times,sum(user_in) as in_num')
                ->where('master_mac', $mac)
                ->whereTime('create_time', 'between', [strtotime($tmp['start_time']), strtotime($tmp['end_time'])])
                ->group('times')
                ->select()->toArray();
            return $this->mergeDetailsNum($result, $dateTime);
        }
    }
    /**
     * [yearArrToeasy 年份数据整理]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    string     $value [description]
     * @return   [type]            [description]
     */
    public function yearArrToeasy($userTime, $dateTime)
    {
        $year = date('Y', strtotime($userTime));
        foreach ($dateTime as $key => $value)
        {
            $value             = $value < 10 ? $year . '-0' . $value : $year . '-' . $value;
            $dateTimeTmp[$key] = $value;
        }
        return $dateTimeTmp;

    }

    /**
     * [getMonth 获取某月天数]
     * @Author   HUI
     * @DateTime 2019-01-14
     * @version  [version]
     * @param    string     $date [description]
     * @return   [type]           [description]
     */
    public function getMonth($date = '')
    {
        $timestamp = strtotime($date);
        if (!empty($timestamp))
        {
            // $timestamp = strtotime(date('Y-m',strtotime($timestamp)));
            // print_r($timestamp);exit();
            $start_time = date('Y-m-1 00:00:00', $timestamp);
            $mdays      = date('t', $timestamp);
            $end_time   = date('Y-m-' . $mdays . ' 23:59:59', $timestamp);
            return ['allDay' => $mdays, 'end_time' => $end_time, 'start_time' => $start_time];
        }
    }

    /**
     * [getLineDetails 获取时间轴数据]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $date_time [description]
     * @return   [type]                [description]
     */
    public function getLineDetails($mac, $dateTime)
    {

        $result = $this->field('FROM_UNIXTIME(create_time, "%m-%d") as times,sum(user_in) as in_num')
            ->where('master_mac', $mac)
            ->whereTime('create_time', -count($dateTime) . ' days')
            ->group('times')
            ->select()->toArray();

        return $this->mergeDetailsNum($result, $dateTime);
    }

    /**
     * [mergeDetailsNum 处理日期数据]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $data [description]
     * @param    [type]     $dateTime [description]
     * @return   [type]               [description]
     */
    public function mergeDetailsNum($data, $dateTime)
    {
        $detailsNum = [];
        $dataTmp    = $this->arrayToEasy($data);
        foreach ($dateTime as $key => $value)
        {
            $num = isset($dataTmp[$value]) ? $dataTmp[$value] : 0;
            // print_r($num);
            $detailsNum[] = $num;
        }
        return $detailsNum;
    }

    /**
     * [arrayToEasy 处理数组]
     * @Author   HUI
     * @DateTime 2019-01-15
     * @version  [version]
     * @param    [type]     $data [description]
     * @return   [type]           [description]
     */
    public function arrayToEasy($data)
    {
        $dataTmp = [];
        if (count($data))
        {
            foreach ($data as $key => $value)
            {
                $dataTmp[$value['times']] = $value['in_num'];
            }
        }
        return $dataTmp;
    }

    /**
     * [getToiletFields 获取单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function getToiletFlowFields($id, $fields = '*')
    {
        if (is_array($id))
        {
            return $this->field($fields)->where($id)->find();

        }
        else
        {
            return $this->field($fields)->where('id', $id)->find();
        }

    }

    /**
     * [getToiletFields 更新单个公厕信息]
     * @Author   HUI
     * @DateTime 2018-11-27
     * @version  [version]
     * @param    [type]     $id     [description]
     * @param    string     $fields [description]
     * @return   [type]             [description]
     */
    public function updateToiletFlowFields($id, $update = [])
    {

        if (is_array($id))
        {
            return $this->where($id)->update($update);
        }
        else
        {
            return $this->where('id', $id)->update($update);
        }
    }

    /**
     * [insertFlowData 插入当日流量到数据库]
     * @param  [type] $data [description]
     * @return [type]       [description]
     */
    public function insertFlowData($data)
    {

        $result = $this->where('mac', $data['mac'])->whereTime('create_time', 'today')->find();
        if ($result)
        {
            $this->where('id', $result['id'])->update(['user_in' => $data['user_in']]);
        }
        else
        {
            // echo "string";
            // print_r($data);
            $result = $this->allowField(true)->save(array_merge($data, ['create_time' => time()]));

            // if ($data['mac'] == '1621911302893' ||$data['mac'] == '1621911306020' ) {

            //     print_r($data);

            //     var_dump($this->getLastInsID());
            // }
        }

    }

    //获取时间轴
    public function getLineDate($type, $dateTime)
    {
        switch ($type)
        {
            case 1:
                // $result = $this->getWeekTime(strtotime($dateTime)); //最近30天
                $result = Time::getMonth();
                break;
            case 2:
                // $result = Time::getYear();
                for ($i = 1; $i <= 12; $i++)
                {
                    $result[] = $i;
                }
                break;
            case 3:
                $result = $this->getWeekTime($dateTime);
                break;
            default:
                $result = Time::getWeek();
                break;
        }

        return $result;
    }

    //获取总数统计
    public function getCountList($data)
    {
        // return  $data;
        if ($data['other_list']) {
            return $data['other_list'];
        }else{

            $count = [];
            foreach ($data['man_list'] as $key => $value) {
                $count[$key] = $value + $data['woman_list'][$key];
            }
            // print_r($count);exit();
            return $count;
        }
    }

    //获取当前时间段的数据
    public function getFlowData($mac, $type, $line)
    {

        $man_mac   = $this->getFlowMac($mac, 3); //男厕
        $woman_mac = $this->getFlowMac($mac, 4); //女厕

        if (!empty($man_mac->toArray()) || !empty($woman_mac->toArray()))
        {

            $man               = $flowData               = $this->getMacFlowCount($man_mac[0]['mac'], $line, $type);
            $data['man_list']  = $this->flowDataToEasy($man['list']);
            $data['man_count'] = $man['sum'];

            $woman               = $flowData               = $this->getMacFlowCount($woman_mac[0]['mac'], $line, $type);
            $data['woman_list']  = $this->flowDataToEasy($woman['list']);
            $data['woman_count'] = $woman['sum'];
            $data['count']       = $data['woman_count'] + $data['man_count'];

            //
            $data['other_list'] = null;

        }
        else
        {

            $other_mac = $this->getFlowMac($mac, 9); //未区分
            $flowMac   = $other_mac[0]['mac'];
            $result    = $flowData    = $this->getMacFlowCount($mac, $line, $type);

            $data['count']       = $result['sum'];
            $data['other_list']  = $this->flowDataToEasy($result['list']);
            // $data['man']         = null;
            $data['man_count']   = 0;
            $data['man_list']    = null;
            $data['woman_list']  = null;
            $data['woman_count'] = 0;
            // $data['woman']       = null;
        }

        return $data;
    }

    //处理数据格式
    public function flowDataToEasy($data)
    {   
        // return $data;
        $result = [];
        foreach ($data as $key => $value) {
            $result[$key] = $value['value'] ? $value['value']:0;
        }
        return $result;
    }

    //获取当前用户标签数量统计
    public function getSatisfactionTagSum($mac, $type, $line)
    {
        $info = (new ToiletModel)->field('user_id,id')->where('mac', $mac)->find();

        $record = new FeedbackRecordModel();
        $tag    = new FeedbackTagModel();
        $tagArr = $tag->where([
            'status' => 1,
            'user_id' => $info['user_id'],
        ])->select();

        $result = [];
        foreach ($line as $key => $value)
        {

            if ($type == 2)
            {

                $year       = date('Y', time());
                $begin_date = date('Y-m', strtotime($year . '-' . $value));
                $time       = $this->getMonth($begin_date);

                $tagRes = [];
                foreach ($tagArr as $k => $v)
                {

                    $count = $record
                        ->where('create_time', 'between time', [
                            date('Y-m-d', strtotime($time['start_time'])),
                            date('Y-m-d', strtotime($time['end_time'])),
                        ])
                        ->where([
                            'tag_id' => $v['id'],
                            'satisfaction' => 0]
                        )->count();

                    $tagRes[$k] = [
                        'tag_name' => $v['tag_name'],
                        'count' => $count,
                    ];
                }

            }
            else
            {

                $tagRes = [];
                foreach ($tagArr as $k => $v)
                {

                    $count = $record
                        ->where('create_time', 'between time', [
                            $value,
                            date('Y-m-d', strtotime("$value +1 days")),
                        ])
                        ->where([
                            'tag_id' => $v['id'],
                            'satisfaction' => 0]
                        )->count();

                    $tagRes[$k] = [
                        'tag_name' => $v['tag_name'],
                        'count' => $count,
                    ];
                }

            }

            $result[$key] = [
                'key' => $value,
                'value' => $tagRes,
            ];
        }

        return $this->dataToEasy($result);

    }







    //
    public function dataToEasy($result,$keys = 'tag_name',$vs = 'count')
    {
        
        $res = [];
        foreach ($result as $key => $value) {


            $data = [];
            $name = [];

            foreach ($value['value'] as $k => $v) {
                $name = array_merge($name,[$v[$keys]]);
                $data = array_merge($data,[$v[$vs]]);
            
            }
            $res[$key] = $data;
        }

        return $this->packageData(['name'=>$name,'val'=>$res]);

    }

    //组装为前端建议格式
    public function packageData($data)
    {
        // print_r($data['val']);exit();

        // return $data;
        $result = [];
        foreach ($data['name'] as $key => $value) {

            $res = [];
            foreach ($data['val'] as $k => $v) {
                $res = array_merge($res,[$v[$key]]);
            }
            
            $result[$key] = $res;
        }

        return ['name'=> $data['name'],'val'=>$result ];

    }


    //获取扇形图数据
    public function getSectorData($data)
    {

        $result = [];
        foreach ($data['name'] as $key => $value) {

            $result[$key] = ['name'=>$value,'value'=>count(array_filter($data['val'][$key]))];
        }
        return $result;


    }


    //获取满意度统计
    public function getSatisfactionData($mac, $type, $line)
    {
        $tid    = (new ToiletModel)->where('mac', $mac)->value('id');
        $record = new FeedbackRecordModel();

        $result = [];
        foreach ($line as $key => $value)
        {

            if ($type == 2)
            {
                $year       = date('Y', time());
                $begin_date = date('Y-m', strtotime($year . '-' . $value));
                $time       = $this->getMonth($begin_date);

                $best = $record->where('create_time', 'between time', [
                    date('Y-m-d', strtotime($time['start_time'])),
                    date('Y-m-d', strtotime($time['end_time'])),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 1)
                    ->sum('satisfaction');

                $good = $record->where('create_time', 'between time', [
                    date('Y-m-d', strtotime($time['start_time'])),
                    date('Y-m-d', strtotime($time['end_time'])),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 2)
                    ->sum('satisfaction');

                $bad = $record->where('create_time', 'between time', [
                    date('Y-m-d', strtotime($time['start_time'])),
                    date('Y-m-d', strtotime($time['end_time'])),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 3)
                    ->sum('satisfaction');

            }
            else
            {

                $best = $record->where('create_time', 'between time', [
                    $value,
                    date('Y-m-d', strtotime("$value +1 days")),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 1)
                    ->sum('satisfaction');

                $good = $record->where('create_time', 'between time', [
                    $value,
                    date('Y-m-d', strtotime("$value +1 days")),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 2)
                    ->sum('satisfaction');

                $bad = $record->where('create_time', 'between time', [
                    $value,
                    date('Y-m-d', strtotime("$value +1 days")),
                ])
                    ->where('t_id', $tid)
                    ->where('satisfaction', 3)
                    ->sum('satisfaction');

            }

            $result[$key] = [
                'key' => $value,
                'value' => [
                    [
                        'name' => '满意',
                        'val' => $best,
                    ],
                    [
                        'name' => '一般',
                        'val' => $good,
                    ],
                    [
                        'name' => '不满意',
                        'val' => $bad,
                    ],
                ],
            ];
        }

        return $this->dataToEasy($result,'name','val');
    }

    //获取流量统计
    public function getMacFlowCount($flowMac, $line, $type)
    {
        $result = [];
        $sum    = 0;
        foreach ($line as $key => $value)
        {

            if ($type == 2)
            {
                $year       = date('Y', time());
                $begin_date = date('Y-m', strtotime($year . '-' . $value));
                $time       = $this->getMonth($begin_date);

                $user_in = $this->where('create_time', 'between time', [
                    date('Y-m-d', strtotime($time['start_time'])),
                    date('Y-m-d', strtotime($time['end_time'])),
                ])
                    ->where('mac', $flowMac)
                    ->sum('user_in');

            }
            else
            {

                $user_in = $this->where('create_time', 'between time', [
                    $value,
                    date('Y-m-d', strtotime("$value +1 days")),
                ])
                    ->where('mac', $flowMac)
                    ->value('user_in');
            }

            $result[$key] = [
                'key' => $value,
                'value' => $user_in,
            ];
            $sum += $user_in;
        }
        $data = [
            'list' => $result,
            'sum' => $sum,
        ];
        return $data;
    }




    public function getFlowMac($mac, $tag_id)
    {

        return (new BandToiletModel)->field('mac,tag_id')
            ->where([
                'master_mac' => $mac,
                'mac_device_type' => 1,
                'tag_id' => $tag_id,
            ])
            ->select();

    }

    //获取时间轴
    public function getWeekTime($dateTime = 0)
    {

        $time = $time != '' ? $time : time();
        $day  = $this->type == 1 ? 30 : 7;
        if ($this->type == 2)
        {
            $ToiletFlow = new ToiletFlowModel();
            $month      = $ToiletFlow->getMonth($time);
            // print_r($month);exit();
            $day  = $month['allDay'];
            $time = strtotime($month['end_time']);
        }
        //具体月份的处理
        //组合数据
        $date = [];
        for ($i = 1; $i <= $day; $i++)
        {
            $date[] = date('m-d', strtotime('+' . $i - $day . ' days', $time));
        }
        return $date;
    }

}
